<!--文件上传组件-->
<template>
  <div class="filesUpload">
    <el-upload
      class="upload-demo"
      drag
      action=""
      :http-request="upload"
      :file-list="fileList"
      :show-file-list="false"
      v-if="administrator"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">直接拖拽文件至这里<em>选择文件</em> </div>
      <template #tip>
        <div class="el-upload__tip"
          ><span v-if="TEMPLATE_DOWNLOAD.includes(props.fileType)">格式见<a :href="templateAddress">模板下载，</a></span
          >请上传 大小不超过 500MB 的文件</div
        >
      </template>
    </el-upload>
    <el-table :data="listedFiles" style="width: 100%">
      <el-table-column prop="fileName" label="文件名" />
      <el-table-column prop="updateTime" label="更新时间" width="280" align="center" />
      <el-table-column label="操作" width="380" align="center">
        <template #default="scope">
          <el-button type="success" @click="onlinePreview(scope.row.id)">在线预览</el-button>
          <el-button type="primary" @click="downloadTheFile(scope.row.id)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script setup>
const TEMPLATE_DOWNLOAD = ["审计对象库", "审计评价体系", "指标库"];
const FILE_NAME_MAPPING = new Map([
  ["审计对象库", "auditObjectLibrary"],
  ["审计评价体系", "auditEvaluationSystem"],
  ["指标库", "indexLibrary"],
]); //模板下载文件名映射
import {
  getAttachmentIDApi,
  getNewFileApi,
  getQueryFileApi,
  getPreviewFileApi,
  getDownloadTheFileApi,
  getAdministratorApi,
} from "@/api/backStageManagement";
import { ElMessage, ElLoading } from "element-plus";
const props = defineProps({
  fileType: {
    type: String, //文件类型
    required: true,
  },
});
const listedFiles = ref([]); //附件列表文件列表
/**
 * 模板下载地址
 * @type {Ref<UnwrapRef<string>>}
 */
const templateAddress = ref(
  new URL(`../../../../public/templateFile/${FILE_NAME_MAPPING.get(props.fileType)}.xlsx`, import.meta.url).href,
);
const fileList = ref([]); //附件
const administrator = ref(false); //是否是管理员
// 判断是否是管理员
const getAdministrator = async () => {
  const data = await getAdministratorApi();
  administrator.value = data.data;
};
getAdministrator(); //判断是否是管理员
const loadingInstance = ref(null); // loding实例
/**
 * 上传文件
 * @param file 文件列表
 * @returns {Promise<void>}
 */
const upload = async (file) => {
  try {
    loadingInstance.value = ElLoading.service({ fullscreen: true, text: "文件上传中，请稍后" });
    const attachmentID = await getAttachmentIDApi({
      fileType: props.fileType,
    }); //先拿到当前页面的文件夹ID
    const formData = new FormData();
    formData.append("file", file.file);
    const docInfo = {
      folderId: attachmentID.data.folderId, //文件夹ID
      fileName: file.file.name, //文件名
      fileType: props.fileType, //文件类型
      cover: "true", //是否覆盖
    };
    formData.append("docInfo", JSON.stringify(docInfo));
    await getNewFileApi(formData); //上传文件
    ElMessage.success("文件上传成功");
    await queryFileList(); //查询文件列表
  } catch (error) {
    ElMessage({
      dangerouslyUseHTMLString: true,
      showClose: true,
      message: error.replace("<br/>", ""), //删除第一个换行符
      type: "error",
      duration: 5000,
    });
  } finally {
    loadingInstance.value.close(); //关闭loading
  }
};
/**
 * 查询文件列表
 * @returns {Promise<void>}
 */
const queryFileList = async () => {
  const { rows } = await getQueryFileApi({
    fileType: props.fileType,
  });
  listedFiles.value = rows;
  // 如果文件列表非空，尝试获取并更新模板下载地址
  if (rows.length) {
    const { msg } = await getDownloadTheFileApi(listedFiles.value[0].id); //返回数据里面始终只有一条文件列表，所以直接取第一项
    templateAddress.value = msg;
  }
};
/**
 * 在线预览
 * @param id
 * @returns {Promise<void>}
 */
const onlinePreview = async (id) => {
  const { msg } = await getPreviewFileApi(id);
  window.open(msg, "_blank");
};
/**
 * 下载文件
 * @param fileId 文件ID
 * @returns {Promise<void>}
 */
const downloadTheFile = async (fileId) => {
  const data = await getDownloadTheFileApi(fileId);
  window.open(data.msg, "_blank");
};
onBeforeMount(async () => {
  await queryFileList(); //查询文件列表
});
</script>

<style scoped lang="less">
.filesUpload {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  .upload-demo {
    width: 400px;
    .el-upload__tip {
      text-align: center;
      a {
        cursor: pointer;
        color: #0d84ff;
      }
    }
  }
}
</style>
